package com.service;

import com.annotation.Component;
import com.annotation.Autowired;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class TimerService {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    public void startCountdown(int seconds) {
        threadPoolExecutor.execute(() -> {
            try {
                for (int i = seconds; i > 0; i--) {
                    System.out.println("倒计时: " + i + " 秒");
                    TimeUnit.SECONDS.sleep(1);
                }
                System.out.println("倒计时结束！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    public void startClock() {
        threadPoolExecutor.execute(() -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    String currentTime = LocalDateTime.now().format(formatter);
                    System.out.println("当前时间: " + currentTime);
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    public void shutdown() {
        threadPoolExecutor.shutdown();
        try {
            if (!threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                threadPoolExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            threadPoolExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}